//
//  FileOperator.m
//  CGNProject
//
//  Created by Michael Shen on 10/8/15.
//  Copyright (c) 2015 Dextrys. All rights reserved.
//

#import "FileOperator.h"

@implementation FileOperator
+ (FileOperator *)defaultOperator{
    static FileOperator *operator = nil;
    if (operator == nil) {
        operator = [[FileOperator alloc] init];
    }
    return operator;
}

-(void)setDataDefaultObject:(NSObject *)object forKey:(NSString *)key{
    [[NSUserDefaults standardUserDefaults] setObject:object forKey:key];
    [[NSUserDefaults standardUserDefaults] synchronize];

}

-(id)dataDefaultObjectForKey:(NSString*)key{
    return [[NSUserDefaults standardUserDefaults] objectForKey:key];
}

-(void)removeDateDefaultObjectForKey:(NSString*)key{
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:key];
}

- (void)setUserInfoObject:(NSObject *)object forKey:(NSString *)key{
    if ([key length] == 0) {
        return;
    }
    NSMutableDictionary *userInfo = [NSMutableDictionary dictionaryWithContentsOfFile:[NSString stringWithFormat:@"%@/Documents/userinfo.plist",NSHomeDirectory()]];
    if (userInfo == nil) {
        userInfo = [NSMutableDictionary dictionary];
    }
    if (object == nil) {
        [userInfo removeObjectForKey:key];
    }else {
        [userInfo setObject:object forKey:key];
    }
    [userInfo writeToFile:[NSString stringWithFormat:@"%@/Documents/userinfo.plist",NSHomeDirectory()] atomically:YES];
}

-(void)deleteUserInfo{
    NSFileManager* fileManager=[NSFileManager defaultManager];
    NSString *uniquePath = [NSString stringWithFormat:@"%@/Documents/userinfo.plist",NSHomeDirectory()];
    BOOL blHave=[[NSFileManager defaultManager] fileExistsAtPath:uniquePath];
    if (!blHave) {
        NSLog(@"no  have");
        return ;
    }else {
        NSLog(@" have");
        BOOL blDele= [fileManager removeItemAtPath:uniquePath error:nil];
        if (blDele) {
            NSLog(@"dele success");
        }else {
            NSLog(@"dele fail");
        }
        
    }
}

- (id)userInfoObjectForKey:(NSString *)key{
    NSDictionary *userInfo = [NSDictionary dictionaryWithContentsOfFile:[NSString stringWithFormat:@"%@/Documents/userinfo.plist",NSHomeDirectory()]];
    return [userInfo objectForKey:key];
}

-(id)userInfo{
    NSDictionary *userInfo = [NSDictionary dictionaryWithContentsOfFile:[NSString stringWithFormat:@"%@/Documents/userinfo.plist",NSHomeDirectory()]];
    return userInfo;
}

//缓存对象到本地缓存目录中
- (BOOL)cacheObjectToFile:(NSObject *)object cacheInterval:(NSTimeInterval)interval forKey:(NSString *)key {
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    //缓存目录
    NSString *cachesDirectory = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"FileCache"];
    if (![[NSFileManager defaultManager] fileExistsAtPath:cachesDirectory]) {
        [[NSFileManager defaultManager] createDirectoryAtPath:cachesDirectory withIntermediateDirectories:YES attributes:nil error:nil];
    }
    //缓存描述
    NSString *cachesDescPath = [cachesDirectory stringByAppendingPathComponent:@"cachDesc.plist"];
    NSMutableDictionary *cachesDesc = [NSMutableDictionary dictionaryWithDictionary:[self readArchiverObjectFromFile:cachesDescPath]];
    //缓存到本地的路径
    NSString *objectCachePath = [cachesDirectory stringByAppendingFormat:@"/%@cache.plist",key];
    //缓存开始时间、缓存有效时间、缓存过期时间、缓存到本地的路径
    NSDictionary *objectCacheDesc = [NSDictionary dictionaryWithObjectsAndKeys:
                                     [NSDate date],@"CacheDate",
                                     [NSNumber numberWithDouble:interval],@"ExpiresInSeconds",
                                     [NSDate dateWithTimeIntervalSinceNow:interval],@"ExpiryDate",
                                     objectCachePath,@"CachePath", nil];
    [cachesDesc setObject:objectCacheDesc forKey:key];
    [self writeArchiverObject:object toFile:objectCachePath];
    [self writeArchiverObject:cachesDesc toFile:cachesDescPath];
    return YES;
}


//获取本地缓存的对象
- (NSObject *)getObjectFromCacheFileForKey:(NSString *)key complete:(void (^)(BOOL needUpdate,id result))complete {
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    //缓存目录
    NSString *cachesDirectory = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"FileCache"];
    //缓存描述
    NSString *cachesDescPath = [cachesDirectory stringByAppendingPathComponent:@"cachDesc.plist"];
    NSMutableDictionary *cachesDesc = [NSMutableDictionary dictionaryWithDictionary:[self readArchiverObjectFromFile:cachesDescPath]];
    //缓存到本地的路径
    NSString *objectCacheDescPath = [cachesDirectory stringByAppendingFormat:@"/%@cache.plist",key];
    if (![[NSFileManager defaultManager] fileExistsAtPath:objectCacheDescPath]) {
        NSString *path = [[NSBundle mainBundle] pathForResource:key ofType:@"plist"];
        complete(YES,[[FileOperator defaultOperator] readArchiverObjectFromFile:path]);
        return [[FileOperator defaultOperator] readArchiverObjectFromFile:path];
    }
    //缓存开始时间、缓存有效时间、缓存过期时间、缓存到本地的路径
    NSDictionary *objectCacheDesc = [cachesDesc objectForKey:key];
    if (objectCacheDesc == nil) {
        complete(YES,[self readArchiverObjectFromFile:objectCacheDescPath]);
        return [self readArchiverObjectFromFile:objectCacheDescPath];
    }
    NSDate *expiryDate = [objectCacheDesc objectForKey:@"ExpiryDate"];
    if ([expiryDate timeIntervalSinceDate:[NSDate date]] > 0) {
        complete(NO,[self readArchiverObjectFromFile:objectCacheDescPath]);
    }
    else {
        complete(YES,[self readArchiverObjectFromFile:objectCacheDescPath]);
    }
    return [self readArchiverObjectFromFile:objectCacheDescPath];
}

- (id)readArchiverObjectFromFile:(NSString *)plistPath {
    if ([[NSFileManager defaultManager] fileExistsAtPath:plistPath]) {
        return [NSKeyedUnarchiver unarchiveObjectWithFile:plistPath];
    }
    return nil;
}

- (void)writeArchiverObject:(id)object toFile:(NSString *)plistPath {
    [NSKeyedArchiver archiveRootObject:object toFile:plistPath];
}

@end
